import {Component, ViewChild} from '@angular/core';
import {AlertController, Content, IonicPage, NavController, NavParams} from "ionic-angular";
import {FoodHomeService} from "./food-home.service";
import {AppUrl, TIME_OUT} from "../../../../app/app.general";
import {AppConfig} from "../../../../app/appConfig";
import {CommonService} from "../../../../app/common.service";

@IonicPage({
  name: 'food-home',
  segment: 'food-home/:param'
})
@Component({
  templateUrl: 'food-home.html',
  selector: 'food-home'
})

export class FoodHomePage {
  @ViewChild(Content) content: Content;

  private image = {//图片请求数据绑定
    imagePrefix: AppUrl.image.getImage,
    type: {
      restaurant: AppUrl.image.type.restaurant,
      food: AppUrl.image.type.food
    },
    imageById: AppUrl.image.getById
  };
  private selectedIndex = 0;
  private shoppingState = false;
  private restaurant = {
    rImg: '',
    fTypes: [
      {
        foods: [
          {
            fId: 1,
            sale: 10,
            fImg: '',
            fName: '',
            fType: '',
            price: 0,
            remark: '',
            fTypeId: 0,
            stock: 0,
            fNum: 0
          }
        ],
        fType: '',
        chosen: false
      },
    ],
    rName: '',
    rAddr: '',
    rId: 0,
    rTel: '',
    workrange: '',
    oldFoodList:{
      orderNo:'',
      trandate:'',
      details:[]
    }
  };//餐馆全部信息
  private foods = [];//根据所选类型展示的菜品信息
  private basket = {//购物车信息
    rId: this.restaurant.rId,
    allPrice: 0,
    foodsList: []
  };
  private tableId;
  private isAdd = false;//标记是否是加菜状态
  private oldFoodList;//未结算订单中的食物列表

  constructor(public navCtrl: NavController,
              public navParam: NavParams,
              private httpService: FoodHomeService,
              private appConfig: AppConfig,
              private cs: CommonService,) {
    if (!localStorage.getItem('dId'))//第一次进入页面，立即存储设备号
      localStorage.setItem('dId', this.cs.getUUID());
    let urlParams = this.navParam.get("param").split('&');
    if (urlParams.length < 2) {
      this.appConfig.presentToast("获取参数失败，请重试");
    }
    else {
      let dId = localStorage.getItem('dId');
      let rId = urlParams[0];
      this.tableId = urlParams[1];
      this.basket.rId = rId;
      if (rId == '' || typeof (rId) === undefined || this.tableId == '' || typeof (this.tableId) === undefined)
        this.appConfig.presentToast("获取参数失败，请重试");
      else {
        this.appConfig.presentLoading('正在获取店铺信息', TIME_OUT);
        this.httpService.getRestaurant({rId: rId, tId: this.tableId, dId: dId}).timeout(TIME_OUT).subscribe(data => {
          this.appConfig.loader.dismiss();
          let temp: any = data;
          if (temp.code == 200) {
            this.restaurant = temp.data;
            this.restaurant.fTypes[0].chosen = true;
            this.foods = this.restaurant.fTypes[0].foods;
          }
          else if (temp.code === 400) {
            this.navCtrl.setRoot('SorryPage', {msg: temp.msg});
          }
          else if (temp.code === 233) {
            this.restaurant = temp.data;
            this.restaurant.fTypes[0].chosen = true;
            this.foods = this.restaurant.fTypes[0].foods;
            this.oldFoodList = this.restaurant.oldFoodList;
            let oldFood = '';
            for (let food of this.oldFoodList.details) {
              let num = +food.fNum + +food.addNum;
              oldFood += food.fName + ' × ' + num + ';'
            }
            this.appConfig.presentAlert('系统提示', temp.msg + '未结算商品包括：' + oldFood, '确定');
            this.isAdd = true;
          }
          else {
            this.appConfig.presentToast(temp.msg);
          }

        }, e => {
          this.cs.httpError(e);
          this.appConfig.loader.dismiss();
        })
      }
    }

  }

  ionViewDidEnter() {
    this.content.scrollToBottom(500);
  }
  scrollToB(){
    this.content.scrollToBottom(500);
  }
  showGoods(i) {
    this.selectedIndex = i;
    document.getElementById('#ID' + i).scrollIntoView(true);
  }

  changeShoppingState() {
    this.shoppingState = !this.shoppingState;
  }

  //添加商品到购物车
  addGood(food) {
    food.fNum++;
    this.basket.allPrice = this.basket.allPrice + food.price;
    let temp = this.basket.foodsList.filter(f => f.fName == food.fName);
    if (temp.length == 0) {
      this.basket.foodsList.push(food);
    }
  }

  //去除购物车商品
  reduceGood(food, i) {
    if (food.fNum > 0) {
      food.fNum--;
      this.basket.allPrice = this.basket.allPrice - food.price;
    }
    if (food.fNum == 0) {
      let temp = this.basket.foodsList.filter(f => f.fName == food.fName);
      if (temp.length > 0) {
        this.basket.foodsList.splice(i, 1);
      }
    }
  }

  //清空购物车商品
  cleanAll() {
    this.basket.allPrice = 0;
    for (let type of this.restaurant.fTypes) {
      for (let food of type.foods) {
        food.fNum = 0;
      }
      this.basket.foodsList.pop();
    }
  }

  //跳转至订单备注页面，压入数据
  goRemark() {
    if (this.basket.foodsList.length == 0)
      this.appConfig.presentToast('请先添加商品到购物车');
    else {
      this.navCtrl.push('FoodRemarkPage', {basket: this.basket, tableId: this.tableId, oldFoodList: this.oldFoodList});
    }
  }
}
